package com.holdtime.jtt809dataservice.client.process;

import com.holdtime.common.utils.general.ApiResponseModel;
import com.holdtime.common.utils.general.BaseResultCode;
import com.holdtime.jtt809dataservice.business.api.ClientLinkService;
import com.holdtime.jtt809dataservice.common.bean.ClientDownDisconnectReqDTO;
import com.holdtime.jtt809dataservice.common.domain.LinkStatusManager;
import com.holdtime.jtt809dataservice.common.event.ClientMessageReceiveEvent;
import com.holdtime.jtt809dataservice.common.process.ClientProtocolProcessor;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import protocol.jtt809.JTT809Packet;
import protocol.jtt809.ProtocolJT809;
import protocol.jtt809.body.DownDisconnectReq;
import protocol.jtt809.body.DownDisconnectRsp;
import protocol.jtt809.body.RawBody;

/**
 * author: sunwei
 * Date: 2025/3/22 23:14
 * Description:
 */
@Slf4j
@Component
public class ClientDownDisconnirctReqProcessor implements ClientProtocolProcessor {
    @Resource
    private ClientLinkService clientLinkService;
    @Resource
    private ProtocolJT809 protocolJT809;

    @Override
    public int getMsgID() {
        return DownDisconnectReq.MSG_ID;
    }

    @Override
    public void process(ClientMessageReceiveEvent event) {
        JTT809Packet<RawBody> source = event.getSource();
        RawBody body = source.getBody();
        DownDisconnectReq downDisconnectReq = new DownDisconnectReq();
        downDisconnectReq.from(body.getRaw());
        ChannelHandlerContext session = event.getChannelHandlerContext();
        log.info("收到上级平台发送的从链路注销请求,jrm:{}", source.getMsgGnsscenterid());
        ClientDownDisconnectReqDTO clientDownDisconnectReqDTO = new ClientDownDisconnectReqDTO();
        clientDownDisconnectReqDTO.setJrm(source.getMsgGnsscenterid());
        clientDownDisconnectReqDTO.setJym(downDisconnectReq.getVerifyCode());
        ApiResponseModel<?> model = clientLinkService.dealDownDisConnectReq(clientDownDisconnectReqDTO);
        if (model.getResultCode() == BaseResultCode.SUCCESS.getCode()) {
            DownDisconnectRsp downDisconnectRsp = new DownDisconnectRsp();
            JTT809Packet<DownDisconnectRsp> packet = protocolJT809.getPacket(downDisconnectRsp, DownDisconnectRsp.MSG_ID, source.getMsgGnsscenterid());
            session.writeAndFlush(packet);
            LinkStatusManager.getCurrent().removeMainLinkStatus(source.getMsgGnsscenterid());
        } else {
            log.error("处理上级平台从链路注销请求异常,msg:{}", model.getMsg());
        }
    }
}
